<?php
//   +----------------------------------------------------------------------
//   | Copyright (c) 2015-2025 http://www.hdphp.cn All rights reserved.
//   | Licensed ( http://www.hdphp.cn/licenses/ )
//   | Author: Jack <sophia2152@qq.com>
//   | 官方网址: http://www.hdphp.cn
//   | 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和使用。
//   | 任何企业和个人不允许对程序代码以任何形式任何目的再发布。
//   +----------------------------------------------------------------------
namespace hdphp\listener\system\timer;

use app\common\services\system\timer\SystemTimerServices;
use hdphp\interfaces\ListenerInterface;
use hdphp\utils\Cron;

/**
 * Class：定时任务
 * 创建人：Jack
 * 创建时间：2024/1/11 11:43
 * @package app\listener\system\timer
 */
class SystemTimer extends Cron implements ListenerInterface
{
    /**
     * 注释：handle
     * 创建人：Jack
     * 创建时间：2024/1/11 14:41
     * @param $event
     * @return void
     */
    public function handle($event): void
    {
        $this->tick(1000, function () {
            $time = time();
            /** @var SystemTimerServices $timerServices */
            $timerServices = app()->make(SystemTimerServices::class);
            $cacheCount = $timerServices->cacheCount();
            if (!$cacheCount) {
                $timerServices->setAllTimerCache();
            }
            $list = $timerServices->cacheList();
            foreach ($list as $item) {
                $mark = (string)($item['mark'] ?? '');
                if (!$mark || !isset($item['is_open'])) {
                    \think\facade\Log::error('定时任务数据异常，数据：' . json_encode($item));
                    continue;
                }
                if ($item['is_open'] == 1) {
                    $data = $timerServices->getTimerCycleTime($item['type'], $item['cycle'], $time, $item['update_execution_time']);
                    if ($time == $data['cycle_time']) {
                        $this->after(1000, function () use ($timerServices, $mark, $time) {
                            // 上次执行时间保存
                            $timerServices->cacheTag()->set($mark, $time);
                            $this->implement_timer($mark);
                        });
                    }
                }
            }
        });
    }

    /**
     * 注释：执行定时任务
     * 创建人：Jack
     * 创建时间：2024/1/13 15:58
     * @param string $mark
     * @return mixed
     */
    public function implement_timer(string $mark)
    {
        switch ($mark) {

            default:
                return true;
        }
    }
}
